<?php

namespace App\Console\Commands\Cruise;

use App\Models\Common\ConfigModel;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyRoleMappingModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Cruise\CruiseCheckCompanyModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckTaskGroupModel;
use App\Models\Cruise\CruiseTemplateModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;

class CleanFsCompany extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:clean-fs-company {departmentId?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '供应商升级洗数据';

    public function handle()
    {
        // od-052ee000c9f2809dc66d7f94bf3019fb 长这样
        $departmentId = (int)$this->argument('departmentId');
        if ($departmentId) {
            $departmentIds = [$departmentId];
        } else {

            // 所有有过稽核任务的供应商
            $departmentIds = CruiseCheckDetailModel::query()
                                                   ->where('companyId', '!=', '')
                                                   ->distinct()
                                                   ->pluck('companyId')
                                                   ->toArray();
        }

        FsCompanyModel
            ::query()
            ->whereIn('departmentId', $departmentIds)
            ->where('newId', 0)
            ->get()
            ->each(function (FsCompanyModel $fsCompanyModel) {

                // fsCompany
                $new = FsCompanyModel::query()->updateOrCreate([
                    'organizationId' => FsCompanyModel::WEB_ORGANIZATION_ID,
                    'name'           => $fsCompanyModel->name,
                    'newId'          => 0,
                ]);

                $new->departmentId = 'SP01' . sprintf("%04d", $new->id);
                $new->save();

                $fsCompanyModel->newId = $new->id;
                $fsCompanyModel->save();

                $this->info("fsCompany id: {$fsCompanyModel->id} to new id: {$new->id}  {$fsCompanyModel->name}");

                // fs_company_user_mappings
                FsCompanyUserMappingModel
                    ::query()
                    ->where('fsCompanyId', $fsCompanyModel->id)
                    ->get()
                    ->each(function (FsCompanyUserMappingModel $fsCompanyUserMappingModel) use ($new) {

                        $mapping = FsCompanyUserMappingModel::query()->updateOrCreate([
                            'rmsUserId'   => $fsCompanyUserMappingModel->rmsUserId,
                            'fsCompanyId' => $new->id,
                        ], [
                            'feishuId'     => '',
                            'businessType' => 0,
                        ]);

                        $this->info("fsCompanyUserMapping rmsUserId: {$fsCompanyUserMappingModel->rmsUserId} ->id:{$mapping->id}");
                    });

                // cruise_check_company
                CruiseCheckCompanyModel
                    ::query()
                    ->where('fsCompanyId', $fsCompanyModel->id)
                    ->get()
                    ->each(function (CruiseCheckCompanyModel $cruiseCheckCompanyModel) use ($new) {

                        $company = CruiseCheckCompanyModel::query()->updateOrCreate([
                            'fsCompanyId' => $new->id,
                        ], [
                            'companyManagerId' => $cruiseCheckCompanyModel->companyManagerId,
                            'kfManagerId'      => $cruiseCheckCompanyModel->kfManagerId,
                        ]);

                        $this->info("cruiseCheckCompanyModel id: {$cruiseCheckCompanyModel->id} -> id: {$company->id}");
                    });

                // cruise_check_task_groups
                CruiseCheckTaskGroupModel
                    ::query()
                    ->where('companyId', $fsCompanyModel->departmentId)
                    ->select('id')
                    ->get()
                    ->each(function (CruiseCheckTaskGroupModel $cruiseCheckTaskGroupModel) use ($new) {
                        $cruiseCheckTaskGroupModel->companyId = $new->departmentId;
                        $cruiseCheckTaskGroupModel->save();

                        $this->info("update cruiseCheckTaskGroupModel id: {$cruiseCheckTaskGroupModel->id} companyId-> {$new->departmentId}");
                    });

                // cruise_check_details
                CruiseCheckDetailModel
                    ::query()
                    ->where('companyId', $fsCompanyModel->departmentId)
                    ->select('id')
                    ->get()
                    ->each(function (CruiseCheckDetailModel $cruiseCheckDetailModel) use ($new) {
                        $cruiseCheckDetailModel->companyId = $new->departmentId;
                        $cruiseCheckDetailModel->save();

                        $this->info("update cruiseCheckDetailModel id: {$cruiseCheckDetailModel->id} companyId-> {$new->departmentId}");
                    });

                // fs_company_role_mappings
                $name = 'companyAudit_' . $fsCompanyModel->departmentId;


                $userIds = (array)json_decode(ConfigModel::query()
                                              ->where('module', 'cruiseCheck')
                                              ->where('name', $name)
                                              ->value('value'), true);

                foreach ($userIds as $userId) {

                    $fsCompanyUserMappingId = FsCompanyUserMappingModel::getNewData($new->id, $userId);

                    FsCompanyRoleMappingModel::query()->updateOrCreate([
                        'fsCompanyId' => $new->id,
                        'rmsUserId'   => $userId,
                        'roleId'      => FsCompanyRoleMappingModel::ROLE_ID_COMPANY_FIRST,
                    ], ['fsCompanyUserMappingId' => $fsCompanyUserMappingId->id ?? 0]);
                }


            });
    }
}
